package part7.interpreter;

import part7.ast.AST;
import part7.ast.BinOp;
import part7.ast.Num;

public class Interpreter extends NodeVisitor {
    private final Parser parser;

    public Interpreter(Parser parser){
        this.parser = parser;
    }

    @Override
    protected int visitBinOp(AST node) throws Exception {
        BinOp binOp = (BinOp)node;
        int res = 0;
        switch (binOp.op.type){
            case PLUS:
                res = visit(binOp.left) + visit(binOp.right);
                break;
            case MINUS:
                res = visit(binOp.left) - visit(binOp.right);
                break;
            case MUL:
                res = visit(binOp.left) * visit(binOp.right);
                break;
            case DIV:
                res = visit(binOp.left) / visit(binOp.right);
                break;
        }
        return res;
    }

    @Override
    protected int visitNum(AST node) {
        return ((Num)node).value;
    }

    public int interpret() throws Exception {
        AST tree = parser.parse();
        return this.visit(tree);
    }
}
